package org.sgx.joptest.client.ui;

import org.sgx.gwteditors.client.impl1.complex.PropertyHaverEditor2;
import org.sgx.joptest.client.editable.EditableUser;
import org.sgx.joptest.client.model.User;
import org.sgx.joptest.client.rpc.GreetingService;
import org.sgx.joptest.client.rpc.GreetingServiceAsync;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
/**
 * 
 * @author sg
 *
 */
public class MainLayout extends Composite {
	private static MainLayout instance;

	public static MainLayout getInstance() {
		if (instance == null)
			instance = new MainLayout();
		return instance;
	}

	private static MainLayoutUiBinder uiBinder = GWT.create(MainLayoutUiBinder.class);

	interface MainLayoutUiBinder extends UiBinder<Widget, MainLayout> {
	}

	@UiField Button b1;
	@UiField VerticalPanel p1;
	private PropertyHaverEditor2<EditableUser> editor;
	
	private MainLayout() {
		initWidget(uiBinder.createAndBindUi(this));
		EditableUser edUser = com.google.gwt.core.shared.GWT.create(EditableUser.class); 
		edUser.setName("Pepe");
		edUser.setLastName("Gonzales");
		editor = new PropertyHaverEditor2<EditableUser>();
		editor.load(edUser); 
		p1.add(editor); 
		
		
		b1.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				doTest1();
			}
		});
	}

	private final GreetingServiceAsync userService = GWT.create(GreetingService.class);

	protected void doTest1() {
		EditableUser edUser = editor.flush();
		User u = EditableUser.to(edUser); 
		
		userService.addUser(u, new AsyncCallback<Long>() {

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("addUser error: " + caught);
			}

			@Override
			public void onSuccess(Long result) {
				Window.alert("addUser error: " + result);
			}
		}); 
		System.out.println("test1");
		userService.greetServer("from jopapp", new AsyncCallback<String>() {

			@Override
			public void onSuccess(String result) {
				Window.alert("success: " + result);
			}

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("error: " + caught);
			}
		});
	}

}
